<template>
  <CardSmall :title="title" :height="height">
    <div ref="chartRef" class="chart"></div>
  </CardSmall>
</template>
<script setup>
  import * as echarts from 'echarts';
  import { echartTheme } from './echartTheme.js';
  import CardSmall from '@/components/CardSmall.vue';

  const props = defineProps({
    height: {
      type: [Number, String],
      default: 300,
    },
    title: {
      type: String,
      default: '温/湿度',
    },
    data: {
      type: Object,
      default: () => {
        return {
          seriesData: [],
        };
      },
    },
  });

  watch(
    () => props.data,
    (newVal) => {
      if (chartInstance.value) {
        renderChart();
      }
    }
  );

  const chartRef = useTemplateRef('chartRef');
  const chartInstance = shallowRef(null);
  const initChart = () => {
    chartInstance.value = echarts.init(chartRef.value, echartTheme);
    renderChart();
    // ...绑定事件等
  };
  const renderChart = () => {
    const { seriesData = [] } = props.data;
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
        },
      },
      legend: {
        show: true,
      },
      grid: {
        top: 64,
      },
      xAxis: {
        type: 'time',
      },
      yAxis: [
        {
          type: 'value',
          name: '温度(°C)',
        },
        {
          type: 'value',
          name: '湿度(%)',
        },
      ],
      series: [...seriesData],
    };
    chartInstance.value.setOption(option);
  };

  onMounted(() => {
    initChart();
    window.addEventListener('resize', resize);
  });
  onUnmounted(() => {
    chartInstance.value?.dispose();
    window.removeEventListener('resize', resize);
  });
  const resize = () => {
    chartInstance.value?.resize();
  };
</script>
<style lang="scss" scoped>
  .chart {
    height: 100%;
  }
</style>
